package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.CartBean;
import com.saifan.wyy_ov.data.bean.OrderBean;
import com.saifan.wyy_ov.data.bean.Orderdetail;
import com.saifan.wyy_ov.data.bean.CartBean.GoodsList;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.utils.PriceUtils;

public class MyCartActivity extends BaseActivity {
    // 总价改变
    final int totalChange = 12;
    protected AdapterCart adapterCart;
    static int DELETESHOPPINGCART = 22;
    private RefreshLayout refreshLayout;
    private android.support.v7.widget.Toolbar toolbar;
    private List<CartBean> cartBeans = new ArrayList<CartBean>();
    private GetData getData;
    private CommonDataBean commonDataBean;
    private int page = 0;
    public ListView listView;
    private CheckBox cb_all;
    private TextView tv_payment_amount;
    private Button bt_pay;
    private RelativeLayout loadlay;
    private ArrayList<OrderBean> orderBeans;
    private ArrayList<Orderdetail> orderdetails;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == totalChange) {
                tv_payment_amount.setText(PriceUtils.getPrice(getTotal()) + "元");
                // 只要有一个取消,全选为false
            }
            if (msg.what == DELETESHOPPINGCART) {

                GoodsList goodsList = (GoodsList) msg.obj;
                delete(goodsList);
                adapterCart.notifyDataSetChanged();


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getData = new GetData();
        setContentView();
        commonDataBean = new CommonDataBean();
        commonDataBean.setCustomerID(getRoomInfoBean().getWYKHDA_ZJ());
        query();
    }

    // 全部支付
    public void allpay(Boolean ischeck) {
        for (CartBean cartBean : cartBeans) {
            for (GoodsList goodsList : cartBean.getGoodsList()) {
                goodsList.setIspay((ischeck));
            }
        }
    }


    // delete
    public void delete(GoodsList goods) {

        for (int i = 0; i < cartBeans.size(); i++) {
            for (int j = 0; j < cartBeans.get(i).getGoodsList().size(); j++) {
                GoodsList goodsList = cartBeans.get(i).getGoodsList().get(j);
                if (goodsList.getID() == goods.getID()) {
                    cartBeans.get(i).getGoodsList().remove(j);

                }
            }

        }


        for (int i = 0; i < cartBeans.size(); i++) {
            if (cartBeans.get(i).getGoodsList().size() < 1) {
                cartBeans.remove(i);


            }

        }


    }

    public void query() {
        // TODO Auto-generated method stub
        commonDataBean.setPage(page);
        if (cartBeans.isEmpty()) {
            loadlay.setVisibility(View.VISIBLE);
        }
        getData.getDataJson(this, Api.GroupBuy.SHOPPINGCARTLIST, commonDataBean, "", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                // TODO Auto-generated method stub
                loadlay.setVisibility(View.GONE);

                List<CartBean> list = new Gson().fromJson(json, new TypeToken<List<CartBean>>() {
                }.getType());
                if (list != null && !list.isEmpty()) {
                    if (page == 0) {
                        cartBeans = list;
                    } else {
                        cartBeans.addAll(list);
                    }
                    adapterCart.setCartBeans(cartBeans);
                    adapterCart.notifyDataSetChanged();
                    tv_payment_amount.setText(PriceUtils.getPrice(getTotal()) + "元");
                } else {
                    if (page > 0) {
                        page--;

                    }
                }
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);

            }

            @Override
            public void onFailed(String str) {
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                if (page > 0) {
                    page--;
                }
            }
        });
    }

    // End Of Content View Elements
    public void pay(View view) {
        Intent intentGoPayActivity = new Intent(MyCartActivity.this, MyCartOrderActivity.class);
        intentGoPayActivity.putExtra("cartBeans", new Gson().toJson(cartBeans));
        startActivity(intentGoPayActivity);
        finish();
    }

    private void setContentView() {
        setContentView(R.layout.activity_my_cart);
        loadlay = (RelativeLayout) findViewById(R.id.loading_lay);
        toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                page++;
                refreshLayout.setLoading(true);
                query();

            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                query();
            }
        });

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        cb_all = (CheckBox) findViewById(R.id.cb_all);
        tv_payment_amount = (TextView) findViewById(R.id.tv_payment_amount);
        bt_pay = (Button) findViewById(R.id.bt_pay);
        listView = (ListView) findViewById(R.id.listView);
        adapterCart = new AdapterCart(MyCartActivity.this, cartBeans, handler);
        listView.setAdapter(adapterCart);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            }
        });
        cb_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean ischeck) {
                // TODO Auto-generated method stub
                if (ischeck) {
                    allpay(true);
                    tv_payment_amount.setText(PriceUtils.getPrice(getTotal()) + "元");
                } else {
                    allpay(false);
                    tv_payment_amount.setText("0 .00元");
                }
                adapterCart.setCartBeans(cartBeans);
                adapterCart.notifyDataSetChanged();
            }
        });
    }


    public double getTotal() {
        double total = 0;
        for (CartBean cartBean : cartBeans) {
            for (GoodsList goodsList : cartBean.getGoodsList()) {
                if (goodsList.isIspay()) {
                    total += goodsList.getGoodsPrice() * goodsList.getCount();
                }
            }
        }
        if (total == 0) {
            bt_pay.setEnabled(false);
            bt_pay.setText("请选择");
        } else {
            bt_pay.setText("结算");
            bt_pay.setEnabled(true);
        }
        return total;
    }
}
